package com.pharmacy.UserManage.service;

import com.pharmacy.UserManage.dao.UserMapper;
import com.pharmacy.UserManage.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(String username, String password) {
        return userMapper.validateUser(username, password);
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.findAllUsers();
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.findUserById(id);
    }

    @Override
    public boolean addUser(User user) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(user.getUsername()) != null) {
            return false;
        }
        return userMapper.insertUser(user) > 0;
    }

    @Override
    public boolean updateUser(User user) {
        // 检查除当前用户外是否有相同用户名的用户
        User existingUser = userMapper.findByUsername(user.getUsername());
        if (existingUser != null && !existingUser.getId().equals(user.getId())) {
            return false;
        }
        return userMapper.updateUser(user) > 0;
    }

    @Override
    public boolean deleteUser(Integer id) {
        return userMapper.deleteUser(id) > 0;
    }

    @Override
    public List<User> getUsersByRole(String role) {
        return userMapper.findUsersByRole(role);
    }

    @Override
    public boolean isUsernameExist(String username) {
        return userMapper.findByUsername(username) != null;
    }
    @Override
    public User findByUsername(String name) {
        return userMapper.findByUsername(name);
    }
}